package com.dingding.gmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dingding.gmall.cart.dto.SkuInfoDTO;
import com.dingding.gmall.cart.dto.UserInfoDTO;
import com.dingding.gmall.cart.feign.ProductFeignService;
import com.dingding.gmall.cart.interceptor.CartInterceptor;
import com.dingding.gmall.cart.service.CartService;
import com.dingding.gmall.cart.vo.Cart;
import com.dingding.gmall.cart.vo.CartItem;
import com.dingding.gmall.common.utils.R;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @program: gmall
 * @description: 购物车
 * @author: liugongding
 * @create: 2021-07-29 11:57
 **/

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gmall:cart";




    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result = (String) cartOps.get(skuId.toString());
        //如果购物车有同样的商品，只需要增加数量
        if (StringUtils.isEmpty(result)) {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoDTO skuInfoDTO = skuInfo.getData("skuInfo", new TypeReference<SkuInfoDTO>() {});
                //2、商品添加购物车
                cartItem.setCheck(true);
                cartItem.setItemCount(num);
                cartItem.setImage(skuInfoDTO.getSkuDefaultImg());
                cartItem.setTitle(skuInfoDTO.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoDTO.getPrice());
            }, executor);
            //3、远程查询sku组合信息
            CompletableFuture<Void> getSkuSaleValuesTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);
            try {
                CompletableFuture.allOf(getSkuInfoTask, getSkuSaleValuesTask).get();
                cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(result, CartItem.class);
            cartItem.setItemCount(cartItem.getItemCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    /**
     * 从缓存获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoDTO userInfoDTO = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoDTO.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoDTO.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoDTO.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    @Override
    public Cart getCart() {
        UserInfoDTO userInfoDTO = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoDTO.getUserId() == null) {
            //未登录
            String cartKey = CART_PREFIX + userInfoDTO.getUserKey();
            //获取临时购物车的所有项
            List<CartItem> tempCartItem = getCartItem(cartKey);
            cart.setCartItems(tempCartItem);
        } else {
            //已登录
            //获取临时购物车
            String tempCartKey = CART_PREFIX + userInfoDTO.getUserKey();
            List<CartItem> tempCartItemList = getCartItem(tempCartKey);
            //如果临时购物车的数据还没有进行合并就合并购物车
            if (!CollectionUtils.isEmpty(tempCartItemList)){
                tempCartItemList.forEach(item -> {
                    addToCart(item.getSkuId(), item.getItemCount());
                });
                clearCart(tempCartKey);
            }
            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            String cartKey = CART_PREFIX + userInfoDTO.getUserId();
            List<CartItem> cartItemList = getCartItem(cartKey);
            cart.setCartItems(cartItemList);
        }
        cart.setCount(cart.getCount());
        cart.setCountType(cart.getCountType());
        cart.setReducePrice(cart.getReducePrice());
        cart.setPayPrice(cart.getPayPrice());
        return cart;
    }

    /**
     * 获取临时购物车或已登录的购物车
     * @param cartKey
     * @return
     */
    public List<CartItem> getCartItem(String cartKey){
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (CollectionUtils.isEmpty(values)) {
            return new ArrayList<>();
        }
        return values.stream().map(item -> JSON.parseObject((String) item, CartItem.class))
                .collect(Collectors.toList());
    }


    @Override
    public CartItem getCartItem(Long skuId) {
        UserInfoDTO userInfoDTO = CartInterceptor.threadLocal.get();
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(result, CartItem.class);
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        if (cartOps == null) {
            return;
        }
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItem cartItem = getCartItem(skuId);
        cartItem.setItemCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),redisValue);
    }

    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCheckedCartItems() {
        UserInfoDTO userInfoDTO = CartInterceptor.threadLocal.get();
        if (userInfoDTO.getUserId() == null) {
            return Lists.newArrayList();
        }
        String cartKey = CART_PREFIX + userInfoDTO.getUserId();
        List<CartItem> cartItems = getCartItem(cartKey);
        Map<Long, BigDecimal> map = null;
        if (!CollectionUtils.isEmpty(cartItems)) {
            List<Long> skuIds = cartItems.stream().map(CartItem::getSkuId).collect(Collectors.toList());
            map = productFeignService.getPrice(skuIds);
            Map<Long, BigDecimal> finalMap = map;
            List<CartItem> collect = cartItems.stream()
                    .filter(CartItem::isCheck)
                    .peek(x -> {
                        //购物项的价格应该是最新的价格
                        BigDecimal price = finalMap.get(x.getSkuId());
                        x.setPrice(price);
                    })
                    .collect(Collectors.toList());
            return collect;
        }
        return Lists.newArrayList();
    }
}
